using System;
using System.Collections.Generic;
using Edge.Common;
using Edge.Common.ComponentModel.Notification;
using Edge.Common.Services;
using Edge.Common.Utils;
using Edge.DAL.Common;
using Edge.DAL.Managers;
using NHibernate;
using NHibernate.Expression;
using Shop.Business.Domain.Customers;

namespace Shop.DAL.Managers
{
    class CustomerAddressManager : AbstractManager<CustomerAddress, int, Customer>, ICustomerAddressManager
    {
        public ICollection<CustomerAddress> Find(FetchOptions fetchOptions, CustomerAddressFilter filter)
        {
            ICriteria criteria = CreateCriteria(fetchOptions);
            AddRestrictions(criteria, filter);
            return criteria.List<CustomerAddress>();
        }

        public int Count(CustomerAddressFilter filter)
        {
            ICriteria criteria = CreateCriteria();
            AddRestrictions(criteria, filter);
            criteria.SetProjection(Projections.RowCount());
            return (int)criteria.List()[0];
        }

        private void AddRestrictions(ICriteria criteria, CustomerAddressFilter filter)
        {
            if (filter.Customer != null)
                criteria.Add(Expression.Eq("Customer", filter.Customer));
            if (!StringUtils.IsBlankOrNull(filter.GetText()) && !(filter.GetText().Trim().Equals("")))
            {
                criteria.Add(Expression.Disjunction()
                                 .Add(Expression.Like("FirstName", "%" + filter.GetText().Trim() + "%"))
                                 .Add(Expression.Like("LastName", "%" + filter.GetText().Trim() + "%"))
                    );
            }
        }

       
    }
}